#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <iostream>
#include <queue>

using std::queue;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* comsumer(void* q){
    printf("consumer thread %ld start...\n", pthread_self());
    queue<int>* my_queue = (queue<int>*)q;
    while(1){
        pthread_mutex_lock(&mutex);
        if(my_queue->empty()){
            printf("no content in queue\n");
        }
        else{
            int i = my_queue->front();
            printf("comsume %d...\n", i);
            my_queue->pop();
        }
        pthread_mutex_unlock(&mutex);
        sleep(4);
    }
    pthread_exit(NULL);
}


void* producer(void* q){
    printf("producer thread %ld start...\n", pthread_self());
    queue<int>* my_queue = (queue<int>*)q;
    while(1){
        pthread_mutex_lock(&mutex);
        int i = rand();
        printf("produce %d...\n", i);
        my_queue->push(i);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}



int main(){
    pthread_t p1, p2, p3, p4, p5;
    queue<int> q;
    pthread_create(&p1, NULL, comsumer, &q);
    pthread_create(&p2, NULL, comsumer, &q);
    pthread_create(&p3, NULL, comsumer, &q);
    pthread_create(&p4, NULL, comsumer, &q);
    pthread_create(&p5, NULL, producer, &q);

    pthread_join(p1, NULL);
    pthread_join(p2, NULL);
    pthread_join(p3, NULL);
    pthread_join(p4, NULL);
    pthread_join(p5, NULL);
}